package middleware

import (
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/spf13/viper"
)

func CORSMiddleware() gin.HandlerFunc {
	hostname := viper.GetString("client.hostname")
	return func(c *gin.Context) {
		c.Writer.Header().Set("Access-Control-Allow-Origin", hostname)    //允许访问的域名
		c.Writer.Header().Set("Access-Control-Max-Age", "86400")          //设置缓存时间
		c.Writer.Header().Set("Access-Control-Allow-Methods", "*")        //设置可以通过访问的方法
		c.Writer.Header().Set("Access-Control-Allow-Headers", "*")        //设置Header
		c.Writer.Header().Set("Access-Control-Allow-Credentials", "true") //设置是否允许发送Cookie

		if c.Request.Method == http.MethodOptions {
			c.AbortWithStatus(200)
		} else {
			c.Next()
		}
	}

}
